package org.zjt.mock.demo.mock.config;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-06-21 下午9:23
 * @see
 */
@Slf4j
public class CustomizedDeSerializer {

    /**
     * localDateTime 序列化器
     */
    public static class LocalDateTimeDeSerializer extends StdScalarDeserializer<LocalDateTime> {

        private static final DateTimeFormatter DATE_TIME_FORMATTER =  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        private static final ZoneId zoneId = ZoneId.systemDefault();

        protected LocalDateTimeDeSerializer() {
            super(LocalDateTime.class);
        }


        @Override
        public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

            JsonNode node = jp.getCodec().readTree(jp);

            JsonNode millisecondsJsonNode = node.get("milliseconds");
            JsonNode formatJsonNode = node.get("format");

            if (!Objects.isNull(millisecondsJsonNode)){
                Long milliseconds = (Long) (millisecondsJsonNode).numberValue();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(new Date(milliseconds).toInstant(), zoneId);
                return localDateTime;
            }else if (!Objects.isNull(formatJsonNode)){
                String format = node.get("format").asText();
                LocalDateTime parse = LocalDateTime.parse(format, DATE_TIME_FORMATTER);
                return parse;
            }
           throw new NullPointerException("数据内容不存在");
        }


    }


}
